/*
   Copyright (C) 2007 Yen-Ju Chen <yjchenx gmail>

   This application is free software; you can redistribute it and/or 
   modify it under the terms of the MIT license. See COPYING.

*/

#import <OrganizeKit/OrganizeKit.h>
#import "KRToolbar.h"
#import "KRActionButton.h"

@implementation KRToolbar
- (void) searchFieldAction: (id) sender
{
	NSMutableArray *subs = AUTORELEASE([[NSMutableArray alloc] init]);
	NSPredicate *predicate;
	NSArray *array = [[searchField stringValue] componentsSeparatedByString: @" "];
	int i, count = [array count];
	NSString *term = nil;
	for (i = 0; i < count; i++)
	{
		term = [[array objectAtIndex: i] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
		if ([term length] > 0)
		{
			predicate = [NSPredicate predicateWithFormat: @"%K CONTAINS %@", qOKTextContent, term];
			[subs addObject: predicate];
		}
	}
	if ([subs count])
	 	predicate = [NSCompoundPredicate andPredicateWithSubpredicates: subs];
	else
		predicate = nil;

	if ([delegate respondsToSelector: @selector(toolbar:searchPredicateDidChange:)])
	{
		[delegate toolbar: self searchPredicateDidChange: predicate];
	}
}

- (void) setActionMenu: (NSMenu *) menu
{
	if (menu)
	{
		[actionButton setEnabled: YES];
		[actionButton setMenu: menu];
	}
	else
	{
		[actionButton setEnabled: NO];
		[actionButton setMenu: nil];
	}
}

- (void) setDelegate: (id) d
{
	ASSIGN(delegate, d);
}

- (id) deleagte
{
	return delegate;
}

/* NSObject */
- (id) initWithFrame: (NSRect) frame
{
	self = [super initWithFrame: frame];

	NSRect rect;

	rect = NSMakeRect(10, 5, 150, NSHeight(frame)-10);
	searchField = [[NSSearchField alloc] initWithFrame: rect];
	[searchField setBezelStyle: NSTextFieldSquareBezel];
	[[searchField cell] setSendsWholeSearchString: YES];
	[searchField setTarget: self];
	[searchField setAction: @selector(searchFieldAction:)];
	[self addSubview: searchField];
	RELEASE(searchField);

	rect = NSMakeRect(NSMaxX(rect)+10, NSMinY(rect), 200, NSHeight(rect));
	tagField = [[NSTextField alloc] initWithFrame: rect];
	[tagField setBezelStyle: NSTextFieldSquareBezel];
	[tagField setAutoresizingMask: NSViewWidthSizable];
	[self addSubview: tagField];
	RELEASE(tagField);

	rect = NSMakeRect(NSWidth(frame)-10-NSHeight(rect), NSMinY(rect), 
	                  NSHeight(rect), NSHeight(rect));
	actionButton = [[KRActionButton alloc] initWithFrame: rect];
	[actionButton setAutoresizingMask: NSViewMinXMargin];
	[actionButton setEnabled: NO];
	[self addSubview: actionButton];
	RELEASE(actionButton);
	
	return self;
}

- (void) dealloc
{
	[super dealloc];
}

@end

